var catCode = ""; 
var shelfInfo = {};
var setting = {
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			onClick: treeClick
		}
};

$(document).ready(function(){
	$.fn.zTree.init($("#catTree"), setting, zNodes);
	
	$("#searchText").keydown(function(){
		if(event.keyCode==13) {
			queryItem();
			return false;
		}
		return true;
	});
	
	$("#search_shelf_name").on("click", function(){
		ShelfDialog.open(function(row){
			shelfInfo = row;
			//如果重新选择了货柜，则清空当前页面数据
			if($("#search_shelf_id") != row.id){
				$("#list-shelf tbody tr").remove();
				$("#list-shelf-new tbody tr").remove();
				$("#list-shelf-down tbody tr").remove();
			}
			if(row.shelfNum){
				$("#shelfNumText").html("共" + row.shelfNum + "个货柜");
				$("#shelfNum").val(row.shelfNum);
			}else{
				$("#shelfNumText").html("共1个货柜");
				$("#shelfNum").val(1);
			}
			$("#shelf-item-nodata").hide();
			$("#search_shelf_id").val(row.id);
			$("#search_shelf_name").val(row.shelfForShort);
			grid_shelf_item.addParam({shelfId:$("#search_shelf_id").val(), nearDay:$("#nearDay").val()});
			//查询留言条数
			selectLeaveWordSize(shelfInfo.id);
			//加载留言数据
			MsgDialog.init(shelfInfo);
		});
	});
	
	$("#nearDay").keydown(function(){
		if(event.keyCode==13) {
			grid_shelf_item.addParam({shelfId:$("#search_shelf_id").val(), nearDay:$("#nearDay").val()});
			return false;
		}
		return true;
	});
	
	loadShelfItem();
	
	//留言的点击事件
	$("#liuyancount").click(function(){
		loadLeaveWord();
	});

});

/**
 * 加载留言数据
 */
function loadLeaveWord(){
	if($("#search_shelf_name").val().length <= 0){
		$.ui.tip("请先选择货柜！");
	}else{
		MsgDialog.open(shelfInfo);
	}
}

/**
 * 查询留言条数
 */
function selectLeaveWordSize(shelfId){
	$.ajax({
	    url: cpath+"/shelfMsg/list/json" ,
	    type: 'POST',
	    dataType:"json",
	    data: {shelfId:shelfId},
	    success: function(resp){
	    	if(resp.code==200){
	    		if(resp.data && resp.data.total > 0){
		    		$("#leaveWordCount").html(resp.data.total);
	    		}
	    	}
	    } ,
	    error : function() {  
    	} 
	});
}

function getItemStatus(id){
	var len = $("#list-shelf tr[data*='\"itemId\":" + id + ",']").length;		
	if(len > 0){
		return "on";
	}
	
	var len = $("#list-shelf-new tr[id='row-list-shelf-new-" +id+ ",']").length;		
	if(len > 0){
		return "new";
	}
	
	var len = $("#list-shelf-down tr[data*='\"itemId\":" + id + ",']").length;		
	if(len > 0){
		return "down";
	}
	
	return "no";
}

function treeClick(e, treeId, treeNode) {
	if($("#search_shelf_name").val() == ""){
		$.ui.tip("请先选择货柜！");
		return;
	}
	if(treeNode.catCode.length <=2){
		$.ui.tip("请至少选择二级分类");
		return;
	}
	
	var id = treeNode.id;
	catCode = treeNode.catCode;
	queryItem();
}

function queryItem(){
	var searchText = $("#searchText").val();
	//加载改分类下的商品数据
	$("#itemList").html('<div style="text-align: center;margin-top: 50px;color:red;">^_^加载中...^_^</div>');
	$.ajax({
	    url: cpath+"/replenishList/getByCatCode",
	    type: 'POST',
	    dataType:"json",
	    data: {catCode: catCode, name:searchText},
	    success: function(resp){
	    	if(resp.code==200){
	    		if(resp.data && resp.data.length > 0){
		    		$("#itemList").html("");
		    		var html = template('tpl-item-row', resp);
		    		$("#itemList").prepend(html);
	    		}else{
		    		$("#itemList").html('<div style="text-align: center;margin-top: 50px;color:red;">^_^无数据.^_^</div>');
	    		}
	    	}else{
	    		$.ui.alert(resp.msg);
	    	}
	    } ,
	    error : function() {  
    	} 
	});
}

function loadShelfItem(){
	var col=[
       {name:"商品名称"
		 ,code:"itemName"
		 ,width:'12%'
		 ,rendertpl:"tpl-item-info"
		},{ name:"现有"
			,code:"itemNum"
			,width:'10px'
		},{ name:"7天"
			,code:"saleNum7day"
			,width:'10px'
		},{ name:"15天"
			,code:"saleNum15day"
			,width:'10px'
		},{ name:"历史"
			,code:"saleNumHistory"
			,width:'10px'
		},{ name:"补货数量"
			,code:""
			,width:'30px'
			,rendertpl:"tpl-item-add-num"
		},{ name:"操作"
			,width:'40px'
			,rendertpl:"tpl-shelf-item-opt"
		}];

	grid_shelf_item = $("#list-shelf").grid({
		cancheck:false,
		cols:col,
		showfuns:false,
		url: cpath+"/shelf/getShelfItem" ,
		data:{shelfId:$("#search_shelf_id").val()},
		noPage:true
	});
	var grid_new = $("#list-shelf-new").grid({
		cancheck:false,
		cols:col,
		showfuns:false,
		notLoadData:true,
		noPage:true
	});
	var grid_down = $("#list-shelf-down").grid({
		cancheck:false,
		cols:col,
		showfuns:false,
		notLoadData:true,
		noPage:true
	});
}

function catItemRowClick(id){
	//debugger
	//#fff000
	//$("#row-list-shelf-" + id).addClass("ref_right_item");
}

function downShelf(ele,id){
	var dataStr = $(ele).parents("tr").attr("data");
	var data = eval("(" + dataStr + ")");
	data.dataStr = dataStr;
	data.opt_type = 2;
	var html = template('tpl-shelf-item-row', data);
	$(ele).parents("tr").remove();
	$("#grid-list-shelf-down").prepend(html);
	$("#catItem-" + id).text("已撤回");
	$(ele).removeClass("goodsitemckbtn_can");
	
	$("#shelf-down-nodata").hide();
	if($("#list-shelf tbody tr").length == 0){
		$("#shelf-item-nodata").show();
	}
}
function upShelf(ele, id){
	var dataStr = $(ele).parents("tr").attr("data");
	var data = eval("(" + dataStr + ")");
	data.dataStr = dataStr;
	data.opt_type = 1;
	var html = template('tpl-shelf-item-row', data);
	$(ele).parents("tr").remove();
	$("#grid-list-shelf").append(html);
	
	$("#catItem-" + id).text("已上架");
	$(ele).removeClass("goodsitemckbtn_can");
	
	if($("#list-shelf-down tbody tr").length == 0){
		$("#shelf-down-nodata").show();
	}
}

function selectItemUp(ele){
	if($(ele).text() != "上新"){
		return false;
	}
	
	var dataStr = $(ele).parents(".goodsitem").attr("data");
	var data = eval("(" + dataStr + ")");
	if(!data.retailPrice){
		return $.ui.tip("此商品没有设置价格，无法上架!");
	}
	
	//判断商品是否在下架列表中
	if($("#list-shelf-down tr[data*='\"itemId\":" + data.id + ",']").length > 0){
		return $.ui.tip("此商品已在下架列表中!");
	}
	//判断商品是否在上架列表中
	if($("#list-shelf tr[data*='\"itemId\":" + data.id + ",']").length > 0){
		return $.ui.tip("此商品已在架，无需上新!");
	} 
	
	data.dataStr = dataStr;
	data.opt_type = 'new';
	var html = template('tpl-shelf-item-row', data);
	$("#grid-list-shelf-new").append(html);
	$(ele).removeClass("goodsitemckbtn_can");
	$(ele).text("已上新");
	
	$("#shelf-new-nodata").hide();
}

function delItem(ele, id){
	$(ele).parents("tr").remove();
	$("#catItem-" + id).text("上新");
	$("#catItem-" + id).addClass("goodsitemckbtn_can");
	
	if($("#list-shelf-new tbody tr").length == 0){
		$("#shelf-new-nodata").show();
	}
}

function updateCount(){
	var total_item_num = 0;
	var total_item_num_new = 0;
	var total_item_num_down = 0;
	
	
	/**
	 * 在架商品
	 */
	var totalFeeShelf = 0;
	var totalFeeCostShelf = 0;
	var rows1 = $("#list-shelf tbody tr");
	var rows2 = $("#list-shelf-new tbody tr");
	$.each(rows1, function(i,row){
		var data = $(row).attr("data");
		data = eval("(" + data + ")");
		var price = data.retailPrice;
		if(data.hasDiscount){
			price = data.discountPrice;
		}
		var itemNum = parseInt(data.itemNum);
		var itemAddNum = $(row).find(".itemAddNum").val();
		if(itemAddNum !="" && itemAddNum > 0){
			itemNum = itemNum + parseInt(itemAddNum);
		}
		price = price * itemNum;
		var costPrice = data.costPrice * itemNum;

		totalFeeShelf = parseFloat(totalFeeShelf) + parseFloat(price);
		totalFeeCostShelf = parseFloat(totalFeeCostShelf) + parseFloat(costPrice);
		
		total_item_num = total_item_num + itemNum;
	});
	
	/**
	 * 上新商品
	 */
	var totalFeeNew = 0;
	var totalFeeCostNew = 0;
	$.each(rows2, function(i,row){
		var data = $(row).attr("data");
		data = eval("(" + data + ")");
		var price = data.retailPrice;
		
		var itemNum = 0;
		var itemAddNum = $(row).find(".itemAddNum").val();
		if(itemAddNum !="" && itemAddNum > 0){
			itemNum = itemNum + parseInt(itemAddNum);
		}
		price = price * itemNum;
		var costPrice = data.costPrice * itemNum;
		
		totalFeeNew = parseFloat(totalFeeNew) + parseFloat(price);
		totalFeeCostNew = parseFloat(totalFeeCostNew) + parseFloat(costPrice);
		
		total_item_num_new = total_item_num_new + itemNum;
	});
	
	
	var totalFee = (totalFeeShelf + totalFeeNew).toFixed(2);
	var totalFeeCost = (totalFeeCostShelf + totalFeeCostNew).toFixed(2);
	$("#totalFee").text(totalFee);
	$("#totalFeeCost").text(totalFeeCost);

	if(parseFloat(totalFee) > 0){
		var totalRate = (parseFloat(totalFee) - parseFloat(totalFeeCost))/parseFloat(totalFee);
		totalRate = parseFloat(totalRate).toFixed(2);
		$("#totalRate").text(totalRate);
	}
	
	/**
	 * 下架商品
	 */
	var rows3 = $("#list-shelf-down tbody tr");
	var totalFeeDown = 0;
	var totalFeeCostDown = 0;
	$.each(rows3, function(i,row){
		var data = $(row).attr("data");
		data = eval("(" + data + ")");
		
		var price = data.retailPrice;
		if(data.hasDiscount){
			price = data.discountPrice;
		}
		
		var itemNum = parseInt(data.itemNum);
		var itemAddNum = $(row).find(".itemAddNum").val();
		if(itemAddNum !="" && itemAddNum > 0){
			itemNum = itemNum + parseInt(itemAddNum);
		}
		price = price * itemNum;
		var costPrice = data.costPrice * itemNum;
		
		totalFeeDown = parseFloat(totalFeeDown) + parseFloat(price);
		totalFeeCostDown = parseFloat(totalFeeCostDown) + parseFloat(costPrice);
		
		total_item_num_down = total_item_num_down + data.itemNum;
	});
	
	var total_item_sku_on = $("#list-shelf tbody tr").length;
	var total_item_sku_new = $("#list-shelf-new tbody tr").length;
	var total_item_sku_down = $("#list-shelf-down tbody tr").length;
	$("#total_item_num").html("总数量: " + total_item_num + "    总SKU: " + total_item_sku_on + "    总金额: " + (totalFeeShelf).toFixed(2));
	$("#total_item_num_new").html("总数量: " + total_item_num_new + "    总SKU: " + total_item_sku_on + "    总金额: " + (totalFeeNew).toFixed(2));
	$("#total_item_num_down").html("总数量: " + total_item_num_down + "    总SKU: " + total_item_sku_down + "    总金额: " + (totalFeeDown).toFixed(2));
	
	$("#totalNum").text(total_item_num + total_item_num_new);
	$("#totalSku").text(total_item_sku_on + total_item_sku_new);
}

$(function(){
	$('#list-shelf,#list-shelf-new').on('DOMNodeRemoved', function(){  
		window.setTimeout(function(){
			updateCount();
		},500);
    }).on('DOMNodeInserted', function(){  
		window.setTimeout(function(){
			updateCount();
		},500);
    }); 

	$("#exoutbtn").on("click", function(){
		var onData = [];
		var newData = [];
		var downData = [];
		
		var rows1 = $("#list-shelf tbody tr");
		var rows2 = $("#list-shelf-new tbody tr");
		var rows3 = $("#list-shelf-down tbody tr");

		var plan_total_num = 0;
		var plan_total_sku = 0;
		var plan_total_fee = 0;
		var plan_total_cost = 0;
		
		var plan_sku_map = {};
		
		$.each(rows1, function(i,row){
			var data = $(row).attr("data");
			data = eval("(" + data + ")");
			data.planNum = $(row).find(".itemAddNum").val();
			//正常
			data.replenishType = 1;
			data.nowNum = data.itemNum;
			onData.push(data);
			
			if(data.planNum !=""){
				plan_total_num = plan_total_num + parseInt(data.planNum);
				plan_sku_map[data.itemId] = 1;
				
				var price = data.retailPrice;
				if(data.hasDiscount){
					price = data.discountPrice;
				}
				var costPrice = data.costPrice;
				plan_total_fee = parseFloat(plan_total_fee) + (parseFloat(price) * data.planNum);
				plan_total_cost = parseFloat(plan_total_cost) + (parseFloat(costPrice) * data.planNum);
			}
		});
		$.each(rows2, function(i,row){
			var data = $(row).attr("data");
			data = eval("(" + data + ")");
			data.planNum = $(row).find(".itemAddNum").val();
			//上新
			data.replenishType = 2;
			newData.push(data);
			
			if(data.planNum !=""){
				plan_total_num = plan_total_num + parseInt(data.planNum);
				plan_sku_map[data.itemId] = 1;
				
				var price = data.retailPrice;
				if(data.hasDiscount){
					price = data.discountPrice;
				}
				var costPrice = data.costPrice;
				plan_total_fee = parseFloat(plan_total_fee) + (parseFloat(price) * data.planNum);
				plan_total_cost = parseFloat(plan_total_cost) + (parseFloat(costPrice) * data.planNum);
			}
		});
		$.each(rows3, function(i,row){
			var data = $(row).attr("data");
			data = eval("(" + data + ")");
			data.planNum = $(row).find(".itemAddNum").val();
			//撤回
			data.replenishType = 3;
			downData.push(data);
		});
		
		if(onData.length == 0 && newData == 0 && downData == 0){
			$.ui.tip("无数据!");
			return;
		}
		
		var totalFee = $("#totalFee").text();
		var totalFeeCost = $("#totalFeeCost").text();
		var totalRate = $("#totalRate").text();
		
		if(totalFee == "NaN"){
			$.ui.tip("总金额不正确!");
			return;
		}
		if(totalFeeCost == "NaN"){
			$.ui.tip("总成本不正确!");
			return;
		}
		if(totalRate == "NaN"){
			$.ui.tip("总毛利率不正确!");
			return;
		}
		
		
		plan_total_sku = BaseUtil.jsonKeyNum(plan_sku_map);
		debugger
		
		var data = {
				"onData":onData, 
				"newData":newData, 
				"downData":downData,
				"totalNum": plan_total_num,
				"totalSku": plan_total_sku,
				"totalFee": plan_total_fee,
				"totalCost": plan_total_cost,
				"shelfNum":$("#shelfNum").val(),
				"shelf": JSON.stringify(shelfInfo)
			};
		data = JSON.stringify(data);
		$.ajax({
		    url: cpath + "/replenishList/add/save" ,
		    type: 'POST',
		    dataType:"json",
		    data: {data:data},
		    success: function(resp){
		    	if(resp.code=="200"){
		    		$.ui.confirm("保存成功!",function(){
		    			window.location.href = cpath + "/replenishList/add";
		    		},function(){
		    			window.location.href = cpath + "/replenishList/add";
		    		});
					return;
		    	}else{
		    		$.ui.alert("错误:" + resp.msg);
					return;
		    	}
		    },
		    error : function() {  
	    	} 
		});
		//BaseUtil.downloadFile(cpath + "/shelf/replenish/save", data);
	});
});